<?php

namespace App\Http\Controllers\Api\Web;

use App\Http\Controllers\Common\ApiController;
use App\Models\Constant\Constant;
use App\Models\Setting\ExchangeCode;
use App\Models\Setting\SysSetting;
use App\Models\User\MemberOrder;
use App\Models\User\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class UserController extends ApiController {

    public function exchangeCode(Request $request){
        $token = $request->header('token');
        $exchangeCode = $request->input('exchangeCode');
        $this->validate($request, [
            'exchangeCode'=>'required'
        ],[],[
            'exchangeCode'=>'兑换码'
        ]);


        $code = ExchangeCode::where(['code'=>$exchangeCode])->first();
        if(empty($code)){
            return responseFail(100001,['msg'=>'兑换码无效！','flag'=>1]);
        }
        if($code->is_finished==1){
            return responseFail(100002,['msg'=>'兑换码已经用过了！','flag'=>2]);
        }
        try {
            DB::beginTransaction();

            $userId = checkJWT($token)['id'];
            $user = User::where('id',$userId)->first();
            if(empty($user)) return  responseFail('未找到合法用户！');

            //兑换码——首试 只能用3次
            if($code->type=='exfirst' && $user->isExBuyFirst()){
                return  responseFail('兑换码——首试 只能购买'.Constant::ExFirst.'次哦！');
            }

            if($code->type=='exfirst'){
                $firstDay = Constant::ExFirstDay;
                $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addDays($firstDay)->format('Y-m-d H:i:s'):Carbon::now()->addDays($firstDay)->format('Y-m-d H:i:s');
            }elseif ($code->type=='exmonth'){
                $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addMonth()->format('Y-m-d H:i:s'):Carbon::now()->addMonth()->format('Y-m-d H:i:s');
            }elseif ($code->type=='exquarter'){
                $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addQuarter()->format('Y-m-d H:i:s'):Carbon::now()->addQuarter()->format('Y-m-d H:i:s');
            }elseif ($code->type=='exyear'){
                $user->ex_expire_time = $user->ex_is_member==1?Carbon::parse($user->ex_expire_time)->addYear()->format('Y-m-d H:i:s'):Carbon::now()->addYear()->format('Y-m-d H:i:s');
            }else{
                throw new \Exception('无效的会员类型');
            }
            $user->ex_type = $code->type;
            $user->ex_is_member = 1;
            $code->is_finished = 1;
            $code->save();
            $user->save();
            MemberOrder::create([
                'user_id'=>$userId,
                'order_number'=>time().uniqid(),
                'fee'=>SysSetting::where('key',$code->type)->first()->val??0,
                //'type'=>Str::replace('ex', '', $code->type),
                /*用code兑换的，订单类型只能是也得是 ex开头的*/
                'type'=>$code->type,
                'is_finished'=>1,
                'is_auto'=>3
            ]);

            DB::commit();
            return responseSuccess(['msg'=>'恭喜您，兑换成功！','flag'=>3]);
        } catch (\Exception $e) {
            DB::rollBack();
            $tip = $e->getFile() . ':' . $e->getLine() . ':' . $e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }


    public function modifyPhone(Request $request){

        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'pwd'=>'required',
            'newpwd'=>'required|confirmed',
        ],[],[
            'pwd'=>'原密码',
            'newpwd'=>'新密码'
        ]);

        $phone = $request->input('phone');
        $pwd = $request->input('pwd');
        $newpwd = $request->input('newpwd');
        $newpwd_confirmation = $request->input('newpwd_confirmation');
        if($newpwd!=$newpwd_confirmation){
            return responseFail('两次密码不一致!');
        }

        $user = User::where(['phone'=>$phone,'pwd_content'=>$pwd])->first();
        if(empty($user)){
            return responseFail('未查找到该用户，手机号或密码错误！');
        }

        User::query()->where(compact('phone'))->update([
            'pwd_content'=>$newpwd,
            'pwd'=>md5($newpwd)
        ]);
        return responseSuccess($user->toArray(),0,'修改密码成功！');
    }

    public function setPhone(Request $request){
        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'pwd'=>'required|confirmed',
        ],[],[
            'pwd'=>'密码'
        ]);

        $phone = $request->input('phone');
        $pwd_content = $pwd = $request->input('pwd');
        $pwd = md5($pwd);

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        User::where(compact('id'))->update(compact('phone','pwd','pwd_content'));
        return responseSuccess();
    }

}
